package utils

import (
	"strings"
)

type ConnConf struct {
	Type string
	User string
	Pass string
	Addr string
	Path string
}

func (this ConnConf) String() string {
	var sb BytesBuilder
	if len(this.Type) > 0 {
		sb.AppendStr(this.Type).AppendStrs("://")
	}
	if len(this.User) > 0 {
		sb.AppendStr(this.User)
	}
	if len(this.Pass) > 0 {
		sb.AppendStr(":").AppendStrs(this.Pass)
	}
	sb.AppendStr(this.Addr)
	if len(this.Path) > 0 {
		sb.AppendStr("/").AppendStrs(this.Path)
	}
	return sb.String()
}

func (this *ConnConf) Parse(str string) {
	idx := strings.Index(str, "://")
	if idx != -1 {
		this.Type = str[:idx]
		str = str[idx+3:]
	}

	strs := strings.SplitN(str, "/", 2)
	connString := strs[0]
	{
		idx := strings.LastIndex(connString, "@")
		if idx != -1 {
			strAuth := connString[:idx]
			strs := strings.SplitN(strAuth, ":", 2)
			this.User = strs[0]
			if len(strs) == 2 {
				this.Pass = strs[1]
			}

			this.Addr = connString[idx+1:]
		} else {
			this.Addr = connString
		}
	}
	if len(strs) > 1 {
		this.Path = strs[1]
	}
}

func ParseConnString(str string) (rval ConnConf) {
	rval.Parse(str)
	return
}
